import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import withAuth from '../components/withAuth';
import { Dialog, NavBar, Tabbar } from 'react-vant';
import './MyLayout.css';
import {
  ArrowLeft,
  BarChartO,
  createFromIconfontCN,
  HomeO,
  ManagerO,
  Search,
  ShopO,
  ShoppingCartO,
} from '@react-vant/icons';
import { useEffect, useState } from 'react';
import { matchRoute, stringStartWith } from '@/utils/common/index';
import routes from '@/routes/routes';
import { useAppDispatch } from '@/hooks/storeHooks';
import { loginout } from '@/utils/redux/slices/authSlice';

const paths = ['/', '/chart', '/my'];

const IconFont = createFromIconfontCN('//at.alicdn.com/t/c/font_4934038_63ux74nr75j.js');

const MyLayout: React.FC = () => {
  const location = useLocation();
  const [value, setValue] = useState(0);
  const [route, setRoute] = useState<any | null>(null);
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  useEffect(() => {
    const path = location.pathname;
    const route = matchRoute(path, routes);
    setRoute(route);
    if (path === '/') {
      setValue(0);
    } else {
      setValue(paths.findIndex((d, i) => i !== 0 && stringStartWith(path, d, true)));
    }
  }, [location.pathname]);

  const handleTabbarChange = (active: string | number) => {
    if (value === active) {
      return;
    }
    navigate(paths[active as number]);
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      title: '登出',
      message: '确认退出吗？',
      onCancel: () => console.log('cancel'),
      onConfirm: () => dispatch(loginout()),
    });
  };

  const handleToSearch = () => {
    navigate('/search');
  };

  return (
    <>
      <div className="my-layout-container">
        {!route?.hideNavbar ? (
          <NavBar
            title={route?.title}
            fixed
            placeholder
            leftArrow={paths.includes(location.pathname) ? null : <ArrowLeft />}
            leftText={paths.includes(location.pathname) ? null : '返回'}
            onClickLeft={() => navigate(-1)}
            rightText={
              location.pathname === '/' ? (
                <Search fontSize={20} onClick={handleToSearch} />
              ) : location.pathname === '/my' ? (
                <IconFont name="icon-tuichu" fontSize={20} onClick={handleLoginOut} />
              ) : null
            }
            onClickRight={() => console.log('按钮')}
          />
        ) : null}
        <Outlet />
        {paths.includes(location.pathname.toLowerCase()) ? (
          <Tabbar value={value} placeholder onChange={handleTabbarChange}>
            <Tabbar.Item icon={<HomeO />}>首页</Tabbar.Item>
            <Tabbar.Item icon={<ShoppingCartO />}>购物车</Tabbar.Item>
            <Tabbar.Item icon={<ManagerO />}>我的</Tabbar.Item>
          </Tabbar>
        ) : null}
      </div>
    </>
  );
};

export default withAuth(MyLayout);
